<?php
namespace app\api\controller;

use alipay\Alipay;
use my\Sendsms;
use think\Db;
use think\facade\Cache;

class Login extends Base {

    //绑定用户发送手机短信
    public function sendSms() {

        $post['tel'] = input('post.tel');
        checkPost($post);

        $sms = new Sendsms();
        $tel = $post['tel'];
        if(!is_tel($tel)) {
            return ajax('无效的手机号',10);
        }

        try {
            $code = mt_rand(100000,999999);
            $insert_data = [
                'tel' => $tel,
                'code' => $code,
                'create_time' => time()
            ];
            $sms_data['tpl_code'] = 'SMS_126362322';
            $sms_data['tel'] = $post['tel'];
            $sms_data['param'] = [
                'code' => $code
            ];
            $exist = Db::table('mp_verify')->where('tel','=',$tel)->find();
            if($exist) {
                if((time() - $exist['create_time']) < 60) {
                    return ajax('1分钟内不可重复发送',11);
                }
                $res = $sms->send($sms_data);
                if($res->Code === 'OK') {
                    Db::table('mp_verify')->where('tel',$tel)->update($insert_data);
                }else {
                    return ajax($res->Message,-1);
                }
            }else {

                $res = $sms->send($sms_data);
                if($res->Code === 'OK') {
                    Db::table('mp_verify')->insert($insert_data);
                }else {
                    return ajax($res->Message,-1);
                }
            }
        }catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();

    }
    //(手机号登录)
    public function mobileLogin() {
        $post['tel'] = input('post.tel');
        $post['code'] = input('post.code');
        checkPost($post);
        try {
            if(!is_tel($post['tel'])) {
                return ajax('invalid tel',10);
            }
            // 检验短信验证码
            $whereCode = [
                ['tel','=',$post['tel']],
                ['code','=',$post['code']]
            ];
            $code_exist = Db::table('mp_verify')->where($whereCode)->find();
            if($code_exist) {
                if((time() - $code_exist['create_time']) > 60*5) {//验证码5分钟过期
                    return ajax('验证码已过期',32);
                }
            }else {
                return ajax('验证码无效',33);
            }
            $whereUser = [
                ['tel','=',$post['tel']]
            ];
            $user_exist = Db::table('mp_user')->where($whereUser)->find();
            $time = time();
            Db::startTrans();
            if($user_exist) { //用户存在更新状态
                $uid = $user_exist['id'];
                $update_user_data = [
                    'last_login_time' => $time
                ];
                Db::table('mp_user')->where($whereUser)->update($update_user_data);
            }else { //用户不存在,创建新用户
                $insert_user_data = [
                    'tel' => $post['tel'],
                    'last_login_time' => $time,
                    'create_time' => $time
                ];
                $uid = Db::table('mp_user')->insertGetId($insert_user_data);
            }
            $token = md5($uid.$time);
            $whereToken = [
                ['uid','=',$uid],
                ['login_type','=',1]
            ];
            $token_exist = Db::table('mp_token')->where($whereToken)->find();
            if(!$token_exist) {
                $insert_data = [
                    'uid' => $uid,
                    'token' => $token,
                    'create_time' => $time,
                    'login_type' => 1
                ];
                Db::table('mp_token')->insert($insert_data);
            }else {
                $insert_data = [
                    'token' => $token,
                    'create_time' => $time
                ];
                Db::table('mp_token')->where($whereToken)->update($insert_data);
            }
//            Db::table('mp_verify')->where($whereCode)->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ajax($e->getMessage(), -1);
        }
        $ret = [
            'token' => $token,
            'uid' => $uid
        ];
        return ajax($ret);
    }
    //(QQ授权登录、支付宝授权登录 绑定手机号)
    public function bindTel() {
        if(request()->isPost()) {
            $post['tel'] = input('post.tel');
            $post['code'] = input('post.code');
            $time = time();
            checkPost($post);
            try {
                if(!is_tel($post['tel'])) {
                    return ajax('无效的手机号',10);
                }
                // 检验短信验证码
                $whereCode = [
                    ['tel','=',$post['tel']],
                    ['code','=',$post['code']]
                ];
                $code_exist = Db::table('mp_verify')->where($whereCode)->find();
                if($code_exist) {
                    if((time() - $code_exist['create_time']) > 60*5) {  //验证码5分钟过期
                        return ajax('验证码已过期',32);
                    }
                }else {
                    return ajax('验证码无效',33);
                }
                $whereUser = [
                    ['tel','=',$post['tel']]
                ];
                $user_exist = Db::table('mp_user')->where($whereUser)->find();
                //2.QQ登录 3.支付宝登录. 用户存在更新状态, 用户不存在,创建新用户
                $uid = null;
                if($user_exist) {
                    $uid = $user_exist['id'];
                    if($this->userinfo['login_type'] === 3) {
                        if($user_exist['alipay_user_id']) {
                            if($user_exist['alipay_user_id'] === $this->userinfo['alipay_user_id']) {
                                return ajax('此手机号已关联此支付宝号, 无需重复绑定',36);
                            }else {
                                return ajax('此手机号已关联其他支付宝号',35);
                            }
                        }
                        Db::table('mp_user')->where($whereUser)->update(
                            [
                                'alipay_user_id' => $this->userinfo['alipay_user_id']
                            ]
                        );
                        Db::table('mp_user_alipay')->where('user_id','=',$this->userinfo['alipay_user_id'])->update(
                            [
                                'uid' => $uid
                            ]
                        );
                    }
                    if($this->userinfo['login_type'] === 2) {
                        if($user_exist['wx_openid']) {
                            if($user_exist['wx_openid'] === $this->userinfo['wx_openid']) {
                                return ajax('此手机号已关联此微信号, 无需重复绑定',39);
                            }else {
                                return ajax('此手机号已关联其他微信号',38);
                            }
                        }
                        Db::table('mp_user')->where($whereUser)->update(
                            [
                                'wx_openid' => $this->userinfo['wx_openid']
                            ]
                        );
                        Db::table('mp_user_wechat')->where('openid','=',$this->userinfo['wx_openid'])->update(
                            [
                                'uid' => $uid
                            ]
                        );
                    }
                }else {
                    $insert_user_data = [
                        'tel' => $post['tel'],
                        'create_time' => $time
                    ];
                    if ($this->userinfo['login_type'] === 3) {
                        $insert_user_data['alipay_user_id'] = $this->userinfo['alipay_user_id'];
                        $uid = Db::table('mp_user')->insertGetId($insert_user_data);
                        Db::table('mp_user_alipay')->where('user_id','=',$this->userinfo['alipay_user_id'])->update(
                            [
                                'uid' => $uid
                            ]
                        );
                    }
                    if ($this->userinfo['login_type'] === 2) {
                        $insert_user_data['wx_openid'] = $this->userinfo['wx_openid'];
                        $uid = Db::table('mp_user')->insertGetId($insert_user_data);
                        Db::table('mp_user_wechat')->where('openid','=',$this->userinfo['wx_openid'])->update(
                            [
                                'uid' => $uid
                            ]
                        );
                    }
                }
                Db::table('mp_token')->where('token','=',$this->userinfo['token'])->update(['uid'=>$uid]);
//                Db::table('mp_verify')->where($whereCode)->delete();
            } catch (\Exception $e) {
                return ajax($e->getMessage(), -1);
            }
            return ajax(['uid'=>$uid]);
        }
    }

    public function logout() {
        //todo 退出账号
    }

    public function checkToken() {
        $token = input('post.token');
        try {
            if(!$token) {
                return ajax('请传入token',-3);
            }else {
                $whereToken = [
                    ['token','=',$token]
                ];
                $token_exist = Db::table('mp_token')->where($whereToken)->find();
                if(!$token_exist) {
                    return ajax('token无效',-3);
                }else {
                    if((time() - $token_exist['create_time']) > config('token_expires_time')) {
                        return ajax('token已过期',-3);
                    }
                }
            }
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        return ajax();
    }





}